package com.yike.user.strategy.login.source;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yike.common.exception.BusinessException;
import com.yike.common.tool.StringUtil;
import com.yike.common.vo.LoginUserInfoVo;
import com.yike.user.entity.Agent;
import com.yike.user.mapper.AgentMapper;
import com.yike.user.utils.ZtskUtil;
import com.yike.user.vo.ztsk.ZtskLoginVo;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Sakura
 * @date 2024/8/20 11:26
 * 账号密码登录
 */
@Component
@Log
public class AgentLoginStrategy implements LoginSourceStrategy {

    @Autowired
    private AgentMapper agentMapper;
    @Autowired
    private ZtskUtil ztskUtil;

    @Override
    public void login(LoginUserInfoVo loginUserInfoVo) {
        // 保存用户类型
        loginUserInfoVo.setType(3);
        // 获取用户代理商信息
        Agent agent = agentMapper.selectOne(Wrappers.lambdaQuery(Agent.class)
                .eq(Agent::getUserId, loginUserInfoVo.getId()));
        if (StringUtil.isNotBlank(loginUserInfoVo.getMobile()) && agent == null) {
            throw new BusinessException("您还没有成为代理商，请联系平台客服成为代理商");
        }
        if (agent != null) {
            // 验证代理商状态
            if (agent.getStatus() == 2) {
                throw new BusinessException("当前代理商已被禁用，请联系平台客服");
            }
            // 添加代理商号到登录信息
            loginUserInfoVo.setAgentId(agent.getId());
            loginUserInfoVo.setAgentNo(agent.getAgentNo());
            loginUserInfoVo.setAgentName(agent.getName());
        }

        // 代理商需要访问智通数控系统
        ZtskLoginVo ztskLoginVo = ztskUtil.login(loginUserInfoVo.getMobile());
        if (!ObjectUtil.isNull(ztskLoginVo)) {
            loginUserInfoVo.setZtskUserId(ztskLoginVo.getUserId());
            loginUserInfoVo.setZtskToken(ztskLoginVo.getToken());
        }

    }
}
